﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Governance.BusinessLogic.Exceptions;
using Sustainalytics.Utils;
using WebApi.OutputCache.V2;
using Sustainalytics.Entities.Governance;
using Sustainalytics.Governance.BusinessLogic.PdfMetadata;
using System.Web.Http.Cors;
using Sustainalytics.AwsS3.Client;
using Sustainalytics.Utils.Configuration;
using Sustainalytics.Governance.BusinessLogic;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.Entities.ConnectionStrings;

namespace Sustainalytics.Governance.Service
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/governanceadminpdfmetadata")]
    [LogControllerFilter(true, true, false)]
	public class GovernanceAdminPdfMetadataController : ApiController
	{
        private IGovernancePdfMetadataManager _governancePdfMetadataManager;
        private IGovernanceManager _gManager;
        private readonly IRepositoryCollection<GovernanceInsightInputFile> _governanceInputFileRepositoryWithFiles;
        static IClaimsChecker _claimsChecker;
        private string baseUrl;
        private readonly string _bucketName;
        //private readonly string _prefix;

        public GovernanceAdminPdfMetadataController()
	    {
            baseUrl = ConfigurationManager.AppSettings["ClientPlatformUrl"];
            var connectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(connectionString));
            var clientWarehouseConnectionString = connectionStringsManager.GetConnectionString(ConnectionStringType.ClientDW);
            var governanceWarehouseConnectionString = connectionStringsManager.GetConnectionString(ConnectionStringType.GovernanceDW);
            var governanceInsightConnectionString = ConfigurationManager.ConnectionStrings["GovernanceInputFile"].ConnectionString;
            
            IGovernancePdfProfileMetadataRepository governancePdfProfileMetadataRepository = new GovernancePdfProfileMetadataRepository(governanceInsightConnectionString);
            _governanceInputFileRepositoryWithFiles = new RepositoryCollectionWithFile<GovernanceInsightInputFile>(governanceInsightConnectionString);
            _governancePdfMetadataManager = new GovernancePdfMetadataManager(governancePdfProfileMetadataRepository, _governanceInputFileRepositoryWithFiles, "");
            _gManager = GovernanceManager.CreateGovernanceManager(clientWarehouseConnectionString, governanceWarehouseConnectionString, governanceInsightConnectionString);

            _bucketName = SettingsHelper.Read("s3-governance-reports", "dev-globalaccess-europe/GovernanceReports");
            //_prefix = SettingsHelper.Read("s3prefix-governance-reports", "Dev");
        }
        static GovernanceAdminPdfMetadataController()
        {
            _claimsChecker = new ClaimsChecker();
        }

        [HttpPost]
        [Route("")]
        public HttpResponseMessage Post([FromBody] GovernancePdfProfileMetadataDto gProfile)
        {
            try
            {
                if (!_claimsChecker.ValidateGovernanceClaim(this))
                {
                    return this.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }

                var userName = (User == null || User.Identity == null ? null : User.Identity.Name);
                var result = _governancePdfMetadataManager.UpdateGovernancePdfProfileMetadata(gProfile, userName);

                //invalidate cache for parent resource 
                var cache = Configuration.CacheOutputConfiguration().GetCacheOutputProvider(Request);
                cache.RemoveStartsWith(Configuration.CacheOutputConfiguration().MakeBaseCachekey("Companies", "Get"));

                return Request.CreateResponse(HttpStatusCode.Created, result);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
            catch (Exception ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
   
        [Route("{id}")]
        public HttpResponseMessage Get(Guid id)
        {
            HttpResponseMessage response;
            try
            {
                //claims for Company Assessment online report and at least one PI indicator claim
                if (!_claimsChecker.ValidateGovernanceClaim(this))
                {
                    return this.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
                var result = _governancePdfMetadataManager.GetProfileByCompany(id, baseUrl);

                response = Request.CreateResponse(HttpStatusCode.OK, result);
            }
            catch (FileNotFoundException ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.NotFound, ex.Message);
            }
            catch (GovernanceProfileNotInUniversesException ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.NotFound, ex.Message);
            }
            catch (Exception ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return response;
        }

        [HttpDelete]
        [Route("")]
        public HttpResponseMessage Delete([FromUri] Guid companyId, GovernancePdfType governancePdfType)
        {
            try
            {
                if (!_claimsChecker.ValidateGovernanceClaim(this))
                {
                    return this.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }

                _governancePdfMetadataManager.DeletePdfMetadataFile(companyId, governancePdfType);
                DeleteProfileFileFromS3(companyId, governancePdfType);
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

        [HttpDelete]
        [Route("")]
        public HttpResponseMessage Delete([FromUri] Guid companyId, Guid fileId)
        {
            try
            {
                if (!_claimsChecker.ValidateGovernanceClaim(this))
                {
                    return this.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }

                _governancePdfMetadataManager.DeletePdfInsightFile(fileId);
                _gManager.DeleteInsightByFileId(fileId, companyId);
                DeleteInsightFileFromS3(companyId, fileId);
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

        bool DeleteProfileFileFromS3(Guid companyId, GovernancePdfType governancePdfType)
        {
            bool isError = false;
            S3ClientSettings _s3ClientSettings;
            _s3ClientSettings = new S3ClientSettings
            {
                AccessKey = SettingsHelper.Read("accesKeyId", "AKIAJKGZZMOFAVOVLHJA"),
                SecretAccessKey = SettingsHelper.Read("awsSecretKey", "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"),
                ServiceEndPoint = SettingsHelper.Read("s3ServiceEndPoint", "https://s3-eu-west-1.amazonaws.com/")
            };

            using (var s3Client = new S3Client(_s3ClientSettings))
            {
                try
                {
                    var fullPath = string.Format("{0}/{1}.pdf", governancePdfType, companyId.ToString());
                    s3Client.DeleteFile(_bucketName, fullPath);
                }
                catch (Exception) { isError = true; }
            }
            return !isError;
        }

        bool DeleteInsightFileFromS3(Guid companyId, Guid fileId)
        {
            bool isError = false;
            S3ClientSettings _s3ClientSettings;
            _s3ClientSettings = new S3ClientSettings
            {
                AccessKey = SettingsHelper.Read("accesKeyId", "AKIAJKGZZMOFAVOVLHJA"),
                SecretAccessKey = SettingsHelper.Read("awsSecretKey", "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"),
                ServiceEndPoint = SettingsHelper.Read("s3ServiceEndPoint", "https://s3-eu-west-1.amazonaws.com/")
            };

            using (var s3Client = new S3Client(_s3ClientSettings))
            {
                try
                {
                    var fullPath = string.Format("{0}/{1}_{2}.pdf", GovernancePdfType.Insight.ToString() , companyId.ToString(), fileId.ToString());
                    s3Client.DeleteFile(_bucketName, fullPath);
                }
                catch (Exception) { isError = true; }
            }
            return !isError;
        }



    }
}

